<?php
include_once("../configure/configure.php");		//--> global var
include_once("../admin/configure/admin.config.inc.php");		//--> global var
include_once("Common.php");
include_once("Files.php");
include_once("../admin/lib/utils/StringUtils.php");				//--> String utils
include_once("../admin/lib/utils/HttpUtils.php");				//--> http utils

$oCommon 	= new Common();
$oFiles		= new Files();		//--> Files

set_time_limit(0);

/* 

 * 0: Advertiser Name, 1: Advertiser URL, 2: MID, 3: Advertiser Description, 4: Link to T&C, 5: Link to Program History,
 * 6: Link to Home Page, 7: Status, 8: Contact Name, 9: Contact Title, 10: State, 11:City, 12:Address, 13:Zip, 14:Country, 15:Phone, 16:Email Address,
 * 17: Commission Terms, 18:Offer, 19:Offer Type, 20:Year Joined, 21:Expiration Date, 22:Return Days, 23:Transaction Update Window, 24:TrueLock,
 * 25:Premium Status, 26:Baseline Commission Terms, 27:Baseline Offer, 28:Baseline Offer Type, 29:Baseline Expiration Date, 30:Baseline Return Days,
 * 31:Baseline Transaction Update Window, 32:Baseline TrueLock

 * 
 */
 
$newMerCount 		= 0;
$existedMerCount 	= 0;
$otherMerIdList		= '';

$merNewFeedPath = "../feed/linkShare/mer/new/";
$merOldFeedPath = "../feed/linkShare/mer/old/";

$arrFileList = $oFiles->listFileName($merNewFeedPath);
foreach($arrFileList as $name){
	$row = 0;
	
	$handle = fopen($merNewFeedPath . $name, "r");
	while ($data = fgetcsv($handle)) {
		if($row == 0){// skip title
			$row++;
			continue;
		}
		
		$merchantName 	= addslashes($data[0]);
		$advertiserId	= $data[2];
		$advertiserURL	= $data[1];
		$advertiserDesc	= mb_convert_encoding($data[3], 'utf8');
		
		$LinktoHomePage	= $data[6];
		
		$ContactName	= $data[8];
		$ContactTitle	= $data[9];
		$State			= $data[10];
		$City			= $data[11];
		$Address		= $data[12];
		$Zip			= $data[13];
		$Country		= $data[14];
		$CSPhone		= $data[15];
		$CSEmail		= $data[16];
		$ExpirationDate	= $data[21];
		
		$merchantID = $oCommon->getColumn(DB_TAG_COUPON, "SELECT ma.merchantId FROM merchant_attributes ma" .
				" WHERE ma.attributeId = 22 AND ma.attributeValue = '$advertiserId'");
		
		if(empty($merchantID)){
			$merchantName = str_replace('\\', '', $merchantName);
			
			$merDescript = '';
			
			$merName 	= addslashes($merchantName);
			$merchantID = $oCommon->getColumn(DB_TAG_COUPON, "SELECT merchantId FROM merchant_alias WHERE alias = '$merName'");
			if(empty($merchantID)){
				$nameId	= StringUtils::getCharNumReplace($merchantName, '_');
				$nameId	= trim($nameId);
				$nameId	= trim($nameId, '_');
				
				$sql_data_array = array(
					'trackingURL' 	=> $LinktoHomePage,
					'displayURL' 	=> $advertiserURL,
					'createdTime' 	=> "UTC_TIMESTAMP()",
					'status' 		=> "1",
					
					'CSPhone' 		=> $CSPhone,
					'CSEmail' 		=> $CSEmail,
					
					'nameId' 		=> $nameId,
					'name' 			=> $merchantName,
					'descript' 		=> $advertiserDesc
				);
					
				$merchantID = $oCommon->insertUpdate(DB_TAG_COUPON, 'merchant', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE trackingURL=Values(trackingURL), " .
						"displayURL=Values(displayURL), CSPhone=Values(CSPhone), CSEmail=Values(CSEmail), descript=Values(descript)");
				echo "Add new merchantID = $merchantID <br>";
				
				$sql_data_array = array(
					'alias' 	=> $merchantName,
					'merchantId' 	=> $merchantID
				);
						
				$oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_alias', $sql_data_array);
				
				$newMerCount++;
			}else{
				$otherMerIdList = ",$merchantID";
			}
			
			
		}else{
//			echo "$merchantName is existed.<br>";
			$existedMerCount++;
		}
		
		if(!empty($merchantID)){
			$merId = $oCommon->getColumn(DB_TAG_COUPON, "SELECT merchantId FROM merchant_images WHERE merchantId = $merchantID");
			if(empty($merId)){
				$logoURL = "http://merchant.linksynergy.com/fs/logo/lg_$advertiserId.jpg";

				if(!HttpUtils::url_exists($logoURL))
					$logoURL = "http://merchant.linksynergy.com/fs/logo/lg_$advertiserId.gif";

				if(!HttpUtils::url_exists($logoURL))
					$logoURL = "http://merchant.linksynergy.com/fs/logo/lg_$advertiserId.png";
			
				if(HttpUtils::url_exists($logoURL)){
					$get_file = file_get_contents($logoURL);
					
					if($get_file)
					{
						$tmpfname 	= tempnam("../tmp/", "mer_logo_");
						$fp = @fopen($tmpfname, "w");
						@fwrite($fp, $get_file);
						@fclose($fp);
						
						$imageinfo = getimagesize($tmpfname);
						$arr_image_extend_name 	= explode('/', $imageinfo['mime']);
						$image_extend_name 		= $arr_image_extend_name[count($arr_image_extend_name) - 1];
								
						$arrImage['file_size']	= filesize($tmpfname);
						
						$arrImage['width']		= $imageinfo[0];
						$arrImage['height']		= $imageinfo[1];
						
						$arrImage['md5']		= md5(file_get_contents($tmpfname));
						$arrImage['extName']	= $image_extend_name;
		
						if(!empty($arrImage['extName'])){
							$sql_data_array = array(
								'extName' 		=> $arrImage['extName'],
								'md5' 			=> $arrImage['md5'],
								'width' 		=> $arrImage['width'],
								'height' 		=> $arrImage['height'],
								'fileSize' 		=> $arrImage['file_size']
							);
								
							$imageid = $oCommon->insertUpdate(DB_TAG_COUPON, 'upload_files', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE width=Values(width), height=Values(height)");
							echo "add new merchant logo image id = $imageid <br>";
							
							$sql_data_array = array(
								'merchantId' 	=> $merchantID,
								'imageId' 		=> $imageid,
								'level' 		=> "0",
							);
								
							$oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_images', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE level=Values(level)");
							
							$imageName = $imageid . '.' . strtolower($arrImage['extName']);
							
							$target = $oFiles->getFullPathByID(IMAGE_PATH_LOGO, $imageid, $imageName);
							
							echo "target = $target <br>";
							
							@copy($tmpfname, $target);
						}
						
						unlink($tmpfname);
					}
				}else{
					echo "get logo failed. logo url = $logoURL <br>";
					
				}
			}
		}
	
		if(!empty($merchantID)){
			
			// add source
			$sql_data_array = array(
				'merchantId' 	=> $merchantID,
				'sourceId' 		=> '3'
			);
					
			$attribteId = $oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_source', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE sourceId=Values(sourceId)");
			
//			echo "is product feed attribteId = $attribteId<br>";
			
			// advertiserId
			$sql_data_array = array(
					'merchantId' 		=> $merchantID,
					'sourceId' 			=> "3",
					'attributeId' 		=> '22',
					'attributeValue' 	=> $advertiserId
				);
					
			$attribteId = $oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_attributes', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE attributeValue=Values(attributeValue)");
			
//			echo "advertiser Id attribteId = $attribteId<br>";
			
			// Expiration Date
			$sql_data_array = array(
					'merchantId' 		=> $merchantID,
					'sourceId' 			=> "3",
					'attributeId' 		=> '41',
					'attributeValue' 	=> $ExpirationDate
				);
					
			$attribteId = $oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_attributes', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE attributeValue=Values(attributeValue)");
			
//			echo "advertiser Id attribteId = $attribteId<br>";
			
			// Country
			$sql_data_array = array(
					'merchantId' 		=> $merchantID,
					'sourceId' 			=> "3",
					'attributeId' 		=> '42',
					'attributeValue' 	=> $Country
				);
					
			$attribteId = $oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_attributes', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE attributeValue=Values(attributeValue)");
			
//			echo "advertiser Id attribteId = $attribteId<br>";
			
			
			// State
			$sql_data_array = array(
					'merchantId' 		=> $merchantID,
					'sourceId' 			=> "3",
					'attributeId' 		=> '25',
					'attributeValue' 	=> $State
				);
					
			$attribteId = $oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_attributes', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE attributeValue=Values(attributeValue)");
			
//			echo "advertiser Id attribteId = $attribteId<br>";

			// City
			$sql_data_array = array(
					'merchantId' 		=> $merchantID,
					'sourceId' 			=> "3",
					'attributeId' 		=> '26',
					'attributeValue' 	=> $City
				);
					
			$attribteId = $oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_attributes', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE attributeValue=Values(attributeValue)");
			
//			echo "advertiser Id attribteId = $attribteId<br>";

			// Address
			$sql_data_array = array(
					'merchantId' 		=> $merchantID,
					'sourceId' 			=> "3",
					'attributeId' 		=> '27',
					'attributeValue' 	=> $Address
				);
					
			$attribteId = $oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_attributes', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE attributeValue=Values(attributeValue)");
			
//			echo "advertiser Id attribteId = $attribteId<br>";

			// zip
			$sql_data_array = array(
					'merchantId' 		=> $merchantID,
					'sourceId' 			=> "3",
					'attributeId' 		=> '28',
					'attributeValue' 	=> $Zip
				);
					
			$attribteId = $oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_attributes', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE attributeValue=Values(attributeValue)");
			
//			echo "advertiser Id attribteId = $attribteId<br>";

			// Contact Name
			$sql_data_array = array(
					'merchantId' 		=> $merchantID,
					'sourceId' 			=> "3",
					'attributeId' 		=> '23',
					'attributeValue' 	=> $ContactName
				);
					
			$attribteId = $oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_attributes', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE attributeValue=Values(attributeValue)");
			
//			echo "advertiser Id attribteId = $attribteId<br>";

			// Contact Title
			$sql_data_array = array(
					'merchantId' 		=> $merchantID,
					'sourceId' 			=> "3",
					'attributeId' 		=> '24',
					'attributeValue' 	=> $ContactTitle
				);
					
			$attribteId = $oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_attributes', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE attributeValue=Values(attributeValue)");
			
//			echo "advertiser Id attribteId = $attribteId<br>";

		}
	}
	
	fclose($handle);
	

}

$oFiles->moveFiles($merNewFeedPath, $merOldFeedPath);

echo "new merchant count: $newMerCount <br>";
echo "existed merchant count: $existedMerCount <br>";
echo "other merchant id list: $otherMerIdList <br>";


